/**
 * 
 */
package cn.tonyqiu.wonuly.client.gui;

import cn.tonyqiu.wonuly.client.i18n.WonulyConstants;
import cn.tonyqiu.wonuly.client.i18n.WonulyMessages;
import cn.tonyqiu.wonuly.client.images.WonulyImageBundle;
import cn.tonyqiu.wonuly.client.rpc.RPCGenerator;

import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

/**
 * This composite display on the top of the App
 * 
 * @author <a href="mailto:tony.qiu.smart@gmail.com">Tony Qiu</a>
 * 
 */
public class TopPanel extends Composite implements ClickListener {

	private static final WonulyConstants constants = Wonuly.constants;
	private static final WonulyImageBundle images = Wonuly.images;
	private static final WonulyMessages messages = Wonuly.messages;
	private HTML signOutLink;
	private HTML aboutLink;
	private HTML welcome = new HTML();

	public TopPanel() {
		signOutLink = new HTML("<a href='javascript:;'>"
				+ constants.topPanelSignOut() + "</a>");
		signOutLink.addClickListener(this);
		aboutLink = new HTML("<a href='javascript:;'>"
				+ constants.topPanelAbout() + "</a>");
		aboutLink.addClickListener(this);

		HorizontalPanel outer = new HorizontalPanel();
		VerticalPanel inner = new VerticalPanel();

		outer.setHorizontalAlignment(HorizontalPanel.ALIGN_RIGHT);
		inner.setHorizontalAlignment(HorizontalPanel.ALIGN_RIGHT);

		HorizontalPanel links = new HorizontalPanel();
		links.setSpacing(4);
		links.add(signOutLink);
		links.add(aboutLink);

		final Image logo = images.logo().createImage();

		outer.add(logo);
		outer.setCellHorizontalAlignment(logo, HorizontalPanel.ALIGN_LEFT);

		inner.add(welcome);
		inner.add(links);
		outer.add(inner);

		initWidget(outer);
		setStyleName("mail-TopPanel");
		links.setStyleName("mail-TopPanelLinks");

		setWelcome();

	}

	private void setWelcome() {
		RPCGenerator.getWonulyAsync().getUsername(new AsyncCallback<String>() {

			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				Window.alert("Excepion" + caught);
			}

			public void onSuccess(String result) {
				welcome.setHTML(messages.topPanelWelcome(result));
			}

		});

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.google.gwt.user.client.ui.ClickListener#onClick(com.google.gwt.user
	 * .client.ui.Widget)
	 */

	public void onClick(Widget src) {
		// TODO Auto-generated method stub
		if (src == signOutLink) {
			Window.alert("To be implemented.");
		} else if (src == aboutLink) {
			AboutDialog adl = new AboutDialog();
			adl.show();
			adl.center();
		}

	}

}
